/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package DATA.iDataSetParts;

import java.io.Serializable;
import java.util.Vector;

/**
 * 
 * @author Bunkowski
 */
public class SubstanceInfo implements Serializable {

	public static final long serialVersionUID = 1L;// 5750224370603869797L;

	public String name;
	public double dt, rt, dtTolerance, rtTolerance;
	public double RtGc = -1;

	public SubstanceInfo(String[] substanceParameter) {
		if (substanceParameter.length != 5) {
			System.out.println("Unknown substance parameter");
		} else {
			name = substanceParameter[0];
			dt = Double.parseDouble(substanceParameter[1].replace(",", "."));
			rt = Double.parseDouble(substanceParameter[2].replace(",", "."));
			dtTolerance = Double.parseDouble(substanceParameter[3].replace(",", "."));
			rtTolerance = Double.parseDouble(substanceParameter[4].replace(",", "."));
		}
	}

	public String[] getSubstanceParameter() {
		return new String[] { name + "", dt + "", rt + "", dtTolerance + "", rtTolerance + "" };
	}

	public Peak getBestHit(Vector<Peak> peaks, String criterion) {
		Vector<Peak> matchingPeaks = new Vector<Peak>();
		for (Peak peak : peaks) {
			if (isPeakThisSubstance(peak)) {
				matchingPeaks.add(peak);
			}
		}
		if (criterion.equals("dt")) {
			return getClosestPeak(matchingPeaks);
		} else if (criterion.equals("intensity")) {
			return getBiggestPeak(matchingPeaks);
		} else {
			return null;
		}
	}

	private Peak getBiggestPeak(Vector<Peak> peaks) {
		Peak closestPeak = null;
		double biggestIntensity = Double.NEGATIVE_INFINITY;

		for (Peak peak : peaks) {
			if (peak.intensity > biggestIntensity) {
				biggestIntensity = peak.intensity;
				closestPeak = peak;
			}
		}
		return closestPeak;
	}

	private Peak getClosestPeak(Vector<Peak> peaks) {
		Peak closestPeak = null;
		double closestDtDistance = 99999;

		for (Peak peak : peaks) {
			if (Math.abs(peak.dt - this.dt) < closestDtDistance) {
				closestPeak = peak;
				closestDtDistance = Math.abs(peak.dt - this.dt);
			}
		}
		return closestPeak;
	}

	private boolean isPeakThisSubstance(Peak peak) {
		if (Math.abs(peak.dt - this.dt) <= dtTolerance && Math.abs(peak.rt - this.rt) <= rtTolerance)
			return true;
		else
			return false;

	}

	public String ObjectToString() {
		String returnValue = "";

		returnValue = "ObjClass : " + this.getClass() + "\r\n";

		returnValue += "name : " + name + "\r\n";
		returnValue += "dt : " + dt + "\r\n";
		returnValue += "rt : " + rt + "\r\n";
		returnValue += "dtTolerance : " + dtTolerance + "\r\n";
		returnValue += "rtTolerance : " + rtTolerance + "\r\n";
		returnValue += "RtGc : " + RtGc + "\r\n";
		returnValue += "EndObject";

		return returnValue;

	}

}
